package io.mvvm.security.handler;

import com.alibaba.fastjson.JSON;
import io.mvvm.common.constant.SystemConstants;
import io.mvvm.common.enumerate.ResponseEnum;
import io.mvvm.common.entity.AjaxResponse;
import io.mvvm.security.utils.JwtUtil;
import io.mvvm.utils.RedisUtil;
import io.mvvm.ws.WebSocketChannelHolder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: seize-login
 * @description: 身份验证成功
 * @author: 潘
 * @create: 2021-05-14 22:39
 **/
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        AjaxResponse.AjaxResponseBuilder builder = AjaxResponse.builder();

        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String token = JwtUtil.generateToken(userDetails.getUsername(), 3000, "_secret");

        if (null != token && token.length() > 0) {

            // 验证当前用户是否在线
            boolean register = WebSocketChannelHolder.isRegister(userDetails.getUsername());

            String key = "";
            long time = 0L;
            if (register) {
                // 在线状态，将token暂存到备份key中
                key = SystemConstants.append(SystemConstants.LOGIN_STATUS_BACK, userDetails.getUsername());
                time = 10 * 1000L;
                builder.token(token).code(ResponseEnum.USER_ONLINE.getCode())
                        .msg(ResponseEnum.USER_ONLINE.getMessage());
            } else {
                key = SystemConstants.append(SystemConstants.LOGIN_STATUS, userDetails.getUsername());
                time = 300 * 1000L;
            }

            Boolean result = redisUtil.set(key, token, time);
            if (result && !register) {
                builder.token(token).code(ResponseEnum.LOGIN_SUCCESS.getCode())
                        .msg(ResponseEnum.LOGIN_SUCCESS.getMessage());
            }
        }

        httpServletResponse.setContentType("application/json; charset=utf-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(builder.build()));
    }



}
